import React, { useState, useEffect } from 'react'
import moment from 'moment'
import { Form, Input, Button, message, Table, Row, Col } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { CheckOutlined, CloseOutlined } from '@ant-design/icons'
import { useHistory } from 'react-router-dom'
import { getUserOrders } from '@/api/order'
import { updateMyInfo } from '@/api/user'
import { setMyInfo } from '@/stores/user'
import { typeOrder, updateUserProps } from '@/types/user'
import { typeOrderProductItem } from '../../../types/cart'
import './index.scss'
import { loadingFn } from '../../../utils/tools'

const pageSize = 5
const UserInfo = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { userInfo } = useSelector((state:any) => state.user)
  const [orders, setOrders] = useState<typeOrder[]>([])
  const [current, setCurrent] = useState(1)
  const [total, setTotal] = useState(0)

  console.log(userInfo)
  useEffect(() => {
    userInfo && loadOrders(1)
  }, [userInfo])

  const loadOrders = async(pageNum:number = current) => {
    loadingFn(async() => {
      const res = await getUserOrders(userInfo.id, {
        pageNum,
        pageSize
      })

      setOrders(res.data.orders)
      setTotal(res.data.total)
      setCurrent(pageNum)
      console.log(res.data.orders[ 0 ])
    })
  }

  /**
   * 点击更新个人信息
   */
  const onclickUpdate = async({ email, password, name }: updateUserProps) => {
    try {
      const res = await updateMyInfo({
        name,
        email,
        password
      })

      localStorage.setItem('token', res.data.token)
      dispatch(setMyInfo(res.data))
      message.success('修改个人信息成功')
    } catch (err:any) {
      message.error(err.response ? err.response.data.msg : err.message)
    }
  }

  const columns = [
    {
      title: '创建时间',
      key: 'createdAt',
      render: (text: Date, record: typeOrder) => (
        <span>{moment(record.createdAt).format('YYYY/MM/DD HH:mm:ss')}</span>
      )
    },
    {
      title: '用户名',
      key: 'user',
      render: (text: string, record: typeOrder) => (
        <span>{record.user.name}</span>
      )
    },
    {
      title: '商品内容',
      dataIndex: 'product',
      render: (text: string, record: typeOrder) => (
        <div>
          {record.productsItems.map((item:typeOrderProductItem) => (
            <div key={item._id}><strong>{item.name}</strong> * {item.qty}</div>
          ))}
        </div>
      )
    },
    {
      title: '价格',
      key: 'price',
      render: (text: string, record: typeOrder) => (
        <div>
          {record.productsPrice} + {record.shippingPrice} = {record.totalPrice}
        </div>
      )
    },
    {
      title: '支付状态',
      dataIndex: 'isPaid',
      render: (text: string, record:typeOrder) => (
        <div>
          {
            record.isPaid
              ? <CheckOutlined style={{ color: '#7cb305' }} />
              : <CloseOutlined style={{ color: '#f5222d' }} />
          }
        </div>
      )
    },
    {
      title: '发货状态',
      dataIndex: 'isDelivered',
      render: (text: string, record:typeOrder) => (
        <div>
          {
            record.isDelivered
              ? <CheckOutlined style={{ color: '#7cb305' }} />
              : <CloseOutlined style={{ color: '#f5222d' }} />
          }
        </div>
      )
    },
    {
      title: '收货状态',
      dataIndex: 'isReceived',
      render: (text: string, record:typeOrder) => (
        <div>
          {
            record.isReceived
              ? <CheckOutlined style={{ color: '#7cb305' }} />
              : <CloseOutlined style={{ color: '#f5222d' }} />
          }
        </div>
      )
    },
    {
      key: 'control',
      render: (text:string, record:typeOrder) => (
        <Button
          onClick={() => { history.push(`/order/${ record._id }/user`) }}
        >
          查看详情
        </Button>
      )
    },
  ]

  return userInfo
    ? (
      <div className="user-home">
        <div className="info">
          <Row gutter={30}>
            <Col className="my-info">
              <h2>我的资料</h2>
              <Form
                autoComplete="off"
                initialValues={{ ...userInfo }}
                labelAlign="left"
                labelCol={{ span: 6 }}
                onFinish={onclickUpdate}
              >
                <Form.Item
                  label="邮箱"
                  name="email"
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label="密码"
                  name="password"
                >
                  <Input.Password />
                </Form.Item>
                <Form.Item
                  label="姓名"
                  name="name"
                >
                  <Input/>
                </Form.Item>
                <Form.Item>
                  <Button
                    className="submit-btn"
                    htmlType="submit"
                    type="primary"
                  >
            修改信息
                  </Button>
                </Form.Item>
              </Form>
            </Col>
            <Col flex={1}>
              <h2>购物情况</h2>
            </Col>
          </Row>

        </div>
        <div className="orders">
          <h2>我的订单</h2>
          <Table
            columns={columns}
            dataSource={orders}
            pagination={{
              position: ['bottomRight'],
              pageSize,
              current,
              total,
              onChange: (current:number) => {
                loadOrders(current)
              }
            }}
            rowKey={(record:typeOrder) => record._id || ''}
          />
        </div>
      </div>
    )
    : null
}

export default UserInfo
